package com.any.sckill.distributed.lock.redis;

import org.springframework.beans.factory.annotation.Autowired;

import com.any.sckill.common.constants.SeckillConstants;

import redis.clients.jedis.Jedis;

public class JedisLock {
	
	@Autowired(required = false)
	private Jedis jedis;
	
	/**
	 * 获取redis客户端对象
	 * @return
	 */
	public Jedis getJedis() {
		return jedis;
	}
	
	private boolean setnx(String key) {
		Long ret = jedis.setnx(key, SeckillConstants.KV_DEFAULT_VALUE);
		return ret > 0 ? true : false;
	}
	
	private boolean del(String key) {
		Long ret = jedis.del(key);
		return ret > 0 ? true : false;
	}
	
	/**
	 * 喂狗
	 * @param key
	 * @param seconds
	 * @return
	 */
	public boolean setExpired(String key, int seconds) {
		Long ret = jedis.expire(key, seconds);
		return ret > 0 ? true : false;
	}
	
	/**
	 * 加锁
	 * @param lockKey
	 * @return
	 */
	public boolean lock(String lockKey) {
		return setnx(lockKey);
	}
	
	/**
	 * 加有效期锁，有效期到自动释放锁，可防止死锁
	 * @param lockKey
	 * @param seconds
	 * @return
	 */
	public boolean lock(String lockKey, int seconds) {
		return setnx(lockKey) ? setExpired(lockKey, seconds) : false;
	}
	
	/**
	 * 释放锁
	 * @param lockKey
	 * @return
	 */
	public boolean unlock(String lockKey) {
		return del(lockKey);
	}

}
